extends Node

# 信号声明
signal hand_updated
signal board_updated
signal mana_changed(player_type: PlayerType, current_mana: int, max_mana: int)
signal health_changed(player_type: PlayerType, health: int)
signal card_played(card: Control, player_type: PlayerType)

# 游戏状态枚举
enum GameState {
	WAITING,
	PLAYER_TURN,
	AI_TURN,
	PLAYING_CARD,
	ATTACKING,
	GAME_OVER
}

# 玩家类型枚举
enum PlayerType {
	PLAYER,
	AI
}

# 游戏状态
@export var current_state: GameState = GameState.WAITING
@export var current_turn: PlayerType = PlayerType.PLAYER
@export var turn_number: int = 1
@export var max_mana: int = 10

# 玩家数据
@export var player_health: int = 30
@export var player_mana: int = 1
@export var player_max_mana: int = 1
@export var ai_health: int = 30
@export var ai_mana: int = 1
@export var ai_max_mana: int = 1

# 卡组和手牌
var player_deck: Array[Control] = []
var player_hand: Array[Control] = []
var player_board: Array[Control] = []
var player_graveyard: Array[Control] = []  # 玩家墓地
var ai_deck: Array[Control] = []
var ai_hand: Array[Control] = []
var ai_board: Array[Control] = []
var ai_graveyard: Array[Control] = []  # AI墓地

# 疲劳伤害系统
var player_fatigue_damage: int = 0  # 玩家疲劳伤害计数器
var ai_fatigue_damage: int = 0  # AI疲劳伤害计数器

# UI引用
var main_scene: Node
var player_hand_container: HBoxContainer
var player_board_container: HBoxContainer
var ai_board_container: HBoxContainer
var player_health_label: Label
var player_mana_label: Label
var ai_health_label: Label
var turn_button: Button
var game_log: RichTextLabel

# 信号定义
signal game_started
signal turn_changed(player_type: PlayerType)
signal game_ended(winner: PlayerType)
signal unit_attacked(attacker: Control, target, player_type: PlayerType)

func _ready():
	print("=== GameManager: _ready函数开始执行 ===")
	
	# 检查Main节点是否存在
	var main_node = get_tree().get_first_node_in_group("main")
	if main_node:
		print("GameManager: ✅ 找到Main节点: ", main_node.name)
	else:
		print("GameManager: ❌ 未找到Main节点!")
	
	# 连接CardManager信号
	if CardManager:
		print("GameManager: CardManager已找到，连接信号")
		CardManager.deck_created.connect(_on_deck_created)
	else:
		print("GameManager: 错误 - CardManager未找到")
	
	# 延迟初始化游戏
	print("GameManager: 准备延迟调用initialize_game")
	call_deferred("initialize_game")

func initialize_game():
	"""初始化游戏"""
	print("=== GameManager: initialize_game 开始执行 ===")
	
	# 延迟5秒后测试提示框功能，确保所有UI都已初始化
	get_tree().create_timer(5.0).timeout.connect(test_tooltip_from_gamemanager)
	
	# 设置随机数种子，确保每次游戏都有不同的随机序列
	randomize()
	
	# 创建玩家卡组
	player_deck = CardManager.create_deck("starter_deck")
	ai_deck = CardManager.create_deck("aggro_deck")
	
	# 洗牌 - 重要：需要将洗牌结果赋值回原变量
	player_deck = CardManager.shuffle_deck(player_deck)
	ai_deck = CardManager.shuffle_deck(ai_deck)
	
	# 抽取起始手牌
	draw_starting_hand()
	
	# 设置初始状态
	current_state = GameState.PLAYER_TURN
	current_turn = PlayerType.PLAYER
	turn_number = 1
	
	# 更新UI
	update_all_ui()
	
	# 发送游戏开始信号
	game_started.emit()
	
	log_message("游戏开始！玩家先手")

func draw_starting_hand():
	"""抽取起始手牌"""
	var starting_hand_size = 3
	
	# 玩家抽牌（不发信号，批量处理）
	for i in starting_hand_size:
		if not player_deck.is_empty():
			var card = player_deck.pop_front()
			if card:
				player_hand.append(card)
	
	# AI抽牌
	for i in starting_hand_size:
		draw_card_for_ai()
	
	# 分发完成后统一发出信号
	hand_updated.emit()
	
	log_message("双方抽取起始手牌")

func draw_card_for_player() -> Control:
	"""为玩家抽一张牌"""
	# 如果牌库为空，尝试重新洗牌
	if player_deck.is_empty():
		if not player_graveyard.is_empty():
			# 重新洗牌：将墓地卡牌重新加入牌库
			log_message("玩家牌库已空，重新洗牌！")
			reshuffle_deck_for_player()
		else:
			# 牌库和墓地都为空，触发疲劳伤害
			player_fatigue_damage += 1
			var damage = player_fatigue_damage
			player_health -= damage
			log_message("玩家疲劳伤害：受到 " + str(damage) + " 点伤害！")
			
			# 发出生命值变化信号
			health_changed.emit(PlayerType.PLAYER, player_health)
			
			# 检查是否死亡
			if player_health <= 0:
				end_game(PlayerType.AI)
			
			return null
	
	var card = player_deck.pop_front()
	
	if card:
		player_hand.append(card)
		log_message("玩家抽到: " + card.card_name)
		
		# 发出手牌更新信号
		hand_updated.emit()
		
		return card
	
	return null

func draw_card_for_ai():
	"""为AI抽一张牌"""
	# 如果牌库为空，尝试重新洗牌
	if ai_deck.is_empty():
		if not ai_graveyard.is_empty():
			# 重新洗牌：将墓地卡牌重新加入牌库
			log_message("AI牌库已空，重新洗牌！")
			reshuffle_deck_for_ai()
		else:
			# 牌库和墓地都为空，触发疲劳伤害
			ai_fatigue_damage += 1
			var damage = ai_fatigue_damage
			ai_health -= damage
			log_message("AI疲劳伤害：受到 " + str(damage) + " 点伤害！")
			
			# 发出生命值变化信号
			health_changed.emit(PlayerType.AI, ai_health)
			
			# 检查是否死亡
			if ai_health <= 0:
				end_game(PlayerType.PLAYER)
			
			return
	
	var card = ai_deck.pop_front()
	ai_hand.append(card)
	log_message("AI抽到一张牌")

func start_turn(player_type: PlayerType):
	"""开始回合"""
	current_turn = player_type
	
	if player_type == PlayerType.PLAYER:
		current_state = GameState.PLAYER_TURN
		# 增加法力水晶
		player_max_mana = min(player_max_mana + 1, max_mana)
		player_mana = player_max_mana
		# 抽牌
		draw_card_for_player()
		# 重置单位状态
		reset_board_units(player_board)
		log_message("玩家回合开始 - 回合 " + str(turn_number))
	else:
		current_state = GameState.AI_TURN
		# 增加法力水晶
		ai_max_mana = min(ai_max_mana + 1, max_mana)
		ai_mana = ai_max_mana
		# 抽牌
		draw_card_for_ai()
		# 重置单位状态
		reset_board_units(ai_board)
		log_message("AI回合开始")
		# 延迟执行AI回合
		call_deferred("execute_ai_turn")
	
	# 更新可打出状态
	update_playable_cards()
	
	# 更新UI
	update_all_ui()
	
	# 发送回合变化信号
	turn_changed.emit(player_type)

func reset_board_units(board: Array[Control]):
	"""重置战场单位状态"""
	for card in board:
		if card:
			card.reset_turn_state()

func end_turn():
	"""结束当前回合"""
	# 在回合结束时进行战场伤害结算
	await resolve_battlefield_combat()
	
	if current_turn == PlayerType.PLAYER:
		log_message("玩家结束回合")
		start_turn(PlayerType.AI)
	else:
		# AI结束回合前检查AI战场卡牌数量
		if ai_board.size() >= 6:
			log_message("[color=yellow]AI战场卡牌数量达到6张，清空战场！[/color]")
			clear_ai_board()
		
		log_message("AI结束回合")
		turn_number += 1
		start_turn(PlayerType.PLAYER)

func execute_ai_turn():
	"""执行AI回合"""
	if current_state != GameState.AI_TURN:
		return
	
	log_message("AI正在思考...")
	
	# 等待一段时间模拟思考
	await get_tree().create_timer(1.0).timeout
	
	# 让AI执行操作
	if AIManager:
		AIManager.execute_turn(ai_hand, ai_board, ai_mana, player_board, player_health)
	
	# AI回合结束
	await get_tree().create_timer(1.0).timeout
	end_turn()

func can_play_card(card: Control, player_type: PlayerType) -> bool:
	"""检查是否可以打出卡牌"""
	if player_type == PlayerType.PLAYER:
		return player_mana >= card.cost and current_state == GameState.PLAYER_TURN
	else:
		return ai_mana >= card.cost and current_state == GameState.AI_TURN

func play_card(card: Control, player_type: PlayerType) -> bool:
	"""打出卡牌"""
	print("GameManager play_card: 开始打出卡牌 ", card.card_name, " 玩家类型: ", player_type)
	
	if not can_play_card(card, player_type):
		log_message("无法打出卡牌: " + card.card_name)
		return false
	
	# 消耗法力
	if player_type == PlayerType.PLAYER:
		player_mana -= card.cost
		# 从手牌移除
		player_hand.erase(card)
		# 发出手牌更新信号
		hand_updated.emit()
	else:
		ai_mana -= card.cost
	
	# 根据卡牌类型执行不同逻辑
	if card.card_type == "unit":
		place_unit_on_board(card, player_type)
	elif card.card_type == "spell":
		execute_spell(card, player_type)
	
	# 更新UI
	update_all_ui()
	
	# 发送信号
	card_played.emit(card, player_type)
	
	log_message(("玩家" if player_type == PlayerType.PLAYER else "AI") + " 打出了: " + card.card_name)
	
	return true

func place_unit_on_board(card: Control, player_type: PlayerType):
	"""将单位放置到战场"""
	print("GameManager place_unit_on_board: 放置单位 ", card.card_name, " 到战场")
	
	if player_type == PlayerType.PLAYER:
		if player_board.size() < 7:  # 战场最多7个单位
			player_board.append(card)
			card.place_on_board()
			card.move_to_board()  # 设置卡牌的战场状态
			# 处理单位特殊效果
			execute_unit_effects(card, player_type)
			print("GameManager place_unit_on_board: 玩家战场现在有 ", player_board.size(), " 个单位")
		else:
			log_message("玩家战场已满！")
	else:
		if ai_board.size() < 7:
			ai_board.append(card)
			card.place_on_board()
			card.move_to_board()  # 设置卡牌的战场状态
			# 处理单位特殊效果
			execute_unit_effects(card, player_type)
			print("GameManager place_unit_on_board: AI战场现在有 ", ai_board.size(), " 个单位")
		else:
			log_message("AI战场已满！")

func execute_spell(card: Control, player_type: PlayerType):
	"""执行法术效果"""
	print("GameManager execute_spell: 执行法术 ", card.card_name, " 效果: ", card.effect)
	
	# 添加视觉反馈 - 让法术卡短暂显示在战场中央
	show_spell_effect(card, player_type)
	
	match card.effect:
		"deal_damage":
			# 简单实现：对敌方英雄造成伤害
			if player_type == PlayerType.PLAYER:
				deal_damage_to_hero(PlayerType.AI, card.effect_value)
				log_message("[color=red]" + card.card_name + " 对敌方造成 " + str(card.effect_value) + " 点伤害[/color]")
			else:
				deal_damage_to_hero(PlayerType.PLAYER, card.effect_value)
				log_message("[color=red]敌方的 " + card.card_name + " 对你造成 " + str(card.effect_value) + " 点伤害[/color]")
		"heal":
			# 治疗己方英雄
			heal_hero(player_type, card.effect_value)
			if player_type == PlayerType.PLAYER:
				log_message("[color=green]" + card.card_name + " 恢复了 " + str(card.effect_value) + " 点生命值[/color]")
			else:
				log_message("[color=green]敌方使用 " + card.card_name + " 恢复了 " + str(card.effect_value) + " 点生命值[/color]")
		"draw_card":
			# 抽牌
			for i in card.effect_value:
				if player_type == PlayerType.PLAYER:
					draw_card_for_player()
				else:
					draw_card_for_ai()
			log_message("[color=blue]" + card.card_name + " 抽取了 " + str(card.effect_value) + " 张卡牌[/color]")
		"buff_health_shield":
			# 魔法护盾：给友方单位+生命值和护盾
			execute_buff_health_shield(player_type, card.effect_value)
			log_message("[color=cyan]" + card.card_name + " 为友方单位提供了护盾[/color]")
		"damage_and_heal":
			# 生命汲取：对敌方造成伤害并恢复生命
			if player_type == PlayerType.PLAYER:
				deal_damage_to_hero(PlayerType.AI, card.effect_value)
				heal_hero(PlayerType.PLAYER, card.effect_value)
				log_message("[color=purple]" + card.card_name + " 造成 " + str(card.effect_value) + " 点伤害并恢复 " + str(card.effect_value) + " 点生命值[/color]")
			else:
				deal_damage_to_hero(PlayerType.PLAYER, card.effect_value)
				heal_hero(PlayerType.AI, card.effect_value)
				log_message("[color=purple]敌方的 " + card.card_name + " 造成 " + str(card.effect_value) + " 点伤害并恢复 " + str(card.effect_value) + " 点生命值[/color]")
		_:
			print("GameManager execute_spell: 未知法术效果: ", card.effect)
			log_message("未知法术效果: " + card.effect)
	
	# 延迟销毁法术卡，让玩家能看到效果
	await get_tree().create_timer(1.5).timeout
	card.destroy_card()

func attack_with_unit(attacker: Control, target, player_type: PlayerType):
	"""单位攻击"""
	if not attacker.is_on_board or attacker.has_summoning_sickness or attacker.has_attacked_this_turn:
		log_message(attacker.card_name + " 无法攻击")
		return
	
	attacker.has_attacked_this_turn = true
	
	if target is Control and target.has_method("take_damage"):
		# 攻击单位
		var target_card = target as Control
		
		# 检查目标是否仍然有效
		if not is_instance_valid(target_card) or target_card.health <= 0:
			log_message("目标单位已无效或已死亡")
			return
		
		attacker.take_damage(target_card.attack)
		target_card.take_damage(attacker.attack)
		log_message(attacker.card_name + " 攻击了 " + target_card.card_name)
		
		# 检查死亡（添加有效性检查）
		if is_instance_valid(attacker) and attacker.health <= 0:
			remove_unit_from_board(attacker, player_type)
		if is_instance_valid(target_card) and target_card.health <= 0:
			var target_player = PlayerType.AI if player_type == PlayerType.PLAYER else PlayerType.PLAYER
			remove_unit_from_board(target_card, target_player)
	else:
		# 攻击敌方英雄
		var target_player = PlayerType.AI if player_type == PlayerType.PLAYER else PlayerType.PLAYER
		deal_damage_to_hero(target_player, attacker.attack)
		log_message(attacker.card_name + " 攻击了敌方英雄")
	
	# 发送攻击信号
	unit_attacked.emit(attacker, target, player_type)
	
	# 更新UI
	update_all_ui()

func remove_unit_from_board(card: Control, player_type: PlayerType):
	"""从战场移除单位"""
	if player_type == PlayerType.PLAYER:
		player_board.erase(card)
	else:
		ai_board.erase(card)
	
	log_message(card.card_name + " 死亡了")
	
	# 将单位送入墓地而不是直接销毁
	send_card_to_graveyard(card, player_type)

func clear_player_board():
	"""清空玩家战场"""
	print("GameManager clear_player_board: 开始清空玩家战场")
	print("GameManager clear_player_board: 当前战场卡牌数量: ", player_board.size())
	
	# 创建要移除的卡牌列表的副本
	var cards_to_remove = player_board.duplicate()
	
	# 逐个移除战场上的卡牌
	for card in cards_to_remove:
		if card and is_instance_valid(card):
			print("GameManager clear_player_board: 移除卡牌: ", card.card_name)
			# 调用现有的移除函数，确保状态一致
			remove_unit_from_board(card, PlayerType.PLAYER)
	
	# 确保战场数组为空
	player_board.clear()
	
	print("GameManager clear_player_board: 清空完成，当前战场卡牌数量: ", player_board.size())
	
	# 触发战场更新信号
	board_updated.emit()
	
	# 记录日志
	log_message("[color=yellow]玩家战场已清空[/color]")

func clear_ai_board():
	"""清空AI战场"""
	print("GameManager clear_ai_board: 开始清空AI战场")
	print("GameManager clear_ai_board: 当前战场卡牌数量: ", ai_board.size())
	
	# 创建要移除的卡牌列表的副本
	var cards_to_remove = ai_board.duplicate()
	
	# 逐个移除战场上的卡牌
	for card in cards_to_remove:
		if card and is_instance_valid(card):
			print("GameManager clear_ai_board: 移除卡牌: ", card.card_name)
			# 调用现有的移除函数，确保状态一致
			remove_unit_from_board(card, PlayerType.AI)
	
	# 确保战场数组为空
	ai_board.clear()
	
	print("GameManager clear_ai_board: 清空完成，当前战场卡牌数量: ", ai_board.size())
	
	# 触发战场更新信号
	board_updated.emit()
	
	# 记录日志
	log_message("[color=yellow]AI战场已清空[/color]")

func check_auto_clear_board(player_type: PlayerType):
	"""检查是否需要自动清空战场（当达到8张卡牌时）"""
	if player_type == PlayerType.PLAYER:
		if player_board.size() >= 8:
			clear_player_board()
	else:
		if ai_board.size() >= 8:
			clear_ai_board()

func deal_damage_to_hero(player_type: PlayerType, damage: int):
	"""对英雄造成伤害"""
	if player_type == PlayerType.PLAYER:
		player_health -= damage
		log_message("玩家受到 " + str(damage) + " 点伤害")
		health_changed.emit(PlayerType.PLAYER, player_health)
		if player_health <= 0:
			end_game(PlayerType.AI)
	else:
		ai_health -= damage
		log_message("AI受到 " + str(damage) + " 点伤害")
		health_changed.emit(PlayerType.AI, ai_health)
		if ai_health <= 0:
			end_game(PlayerType.PLAYER)

func heal_hero(player_type: PlayerType, amount: int):
	"""治疗英雄"""
	if player_type == PlayerType.PLAYER:
		player_health = min(player_health + amount, 30)
		log_message("玩家恢复 " + str(amount) + " 点生命值")
		health_changed.emit(PlayerType.PLAYER, player_health)
	else:
		ai_health = min(ai_health + amount, 30)
		log_message("AI恢复 " + str(amount) + " 点生命值")
		health_changed.emit(PlayerType.AI, ai_health)

func end_game(winner: PlayerType):
	"""结束游戏"""
	print("🎮 GameManager: end_game被调用，胜利者: ", winner)
	current_state = GameState.GAME_OVER
	
	if winner == PlayerType.PLAYER:
		log_message("恭喜！你获得了胜利！")
		print("🎮 GameManager: 玩家胜利，准备发送game_ended信号")
	else:
		log_message("很遗憾，你失败了...")
		print("🎮 GameManager: AI胜利，准备发送game_ended信号")
	
	# 发送游戏结束信号
	print("🎮 GameManager: 即将发送game_ended信号")
	game_ended.emit(winner)
	print("🎮 GameManager: game_ended信号已发送")

# 测试方法：手动触发游戏结束
func test_trigger_victory():
	"""测试触发玩家胜利"""
	print("🎮 GameManager: 手动触发玩家胜利测试")
	end_game(PlayerType.PLAYER)

func test_trigger_defeat():
	"""测试触发玩家失败"""
	print("🎮 GameManager: 手动触发玩家失败测试")
	end_game(PlayerType.AI)

func clean_invalid_cards():
	"""清理无效的卡牌对象"""
	var valid_cards: Array[Control] = []
	var invalid_count = 0
	
	for card in player_hand:
		if is_instance_valid(card):
			valid_cards.append(card)
		else:
			invalid_count += 1
	
	if invalid_count > 0:
		player_hand = valid_cards

func update_playable_cards():
	"""更新可打出的卡牌状态"""
	# 先清理无效的卡牌
	clean_invalid_cards()
	
	for card in player_hand:
		card.set_playable(can_play_card(card, PlayerType.PLAYER))

func update_all_ui():
	"""更新所有UI"""
	print("GameManager update_all_ui: 开始更新所有UI")
	
	# 更新法力值
	mana_changed.emit(PlayerType.PLAYER, player_mana, player_max_mana)
	mana_changed.emit(PlayerType.AI, ai_mana, ai_max_mana)
	
	# 更新生命值
	health_changed.emit(PlayerType.PLAYER, player_health)
	health_changed.emit(PlayerType.AI, ai_health)
	
	# 更新战场显示
	board_updated.emit()
	
	print("GameManager update_all_ui: UI更新完成")
	
	# 检查是否需要自动结束回合
	call_deferred("check_auto_end_turn")

func log_message(message: String):
	"""记录游戏日志"""
	print("[GameLog] " + message)
	
	# 如果有游戏日志UI，在这里更新
	if game_log:
		game_log.append_text(message + "\n")

func _on_deck_created(deck_name: String):
	"""当卡组创建完成时的回调"""
	pass

func _on_turn_button_pressed():
	"""结束回合按钮被点击"""
	if current_state == GameState.PLAYER_TURN:
		end_turn()

func _on_card_clicked(card: Control):
	"""卡牌被点击"""
	print("卡牌被点击: ", card.card_name)
	if current_state == GameState.PLAYER_TURN and card.is_in_hand:
		if can_play_card(card, PlayerType.PLAYER):
			play_card(card, PlayerType.PLAYER)
		else:
			log_message("法力不足或无法打出: " + card.card_name)

func _on_card_played(card: Control):
	"""卡牌被打出时的回调"""
	if current_state == GameState.PLAYER_TURN:
		play_card(card, PlayerType.PLAYER)

func get_game_state() -> Dictionary:
	"""获取游戏状态"""
	return {
		"current_state": current_state,
		"current_turn": current_turn,
		"turn_number": turn_number,
		"player_health": player_health,
		"player_mana": player_mana,
		"player_max_mana": player_max_mana,
		"ai_health": ai_health,
		"ai_mana": ai_mana,
		"ai_max_mana": ai_max_mana,
		"player_hand_size": player_hand.size(),
	}

func execute_unit_effects(card: Control, player_type: PlayerType):
	"""执行单位卡的特殊效果"""
	match card.effect:
		"charge":
			# 冲锋：可以立即攻击
			card.has_summoning_sickness = false
			log_message(card.card_name + " 获得冲锋能力！")
		"stealth":
			# 潜行：添加潜行标记
			card.set_meta("has_stealth", true)
			log_message(card.card_name + " 进入潜行状态！")
		"taunt":
			# 嘲讽：添加嘲讽标记
			card.set_meta("has_taunt", true)
			log_message(card.card_name + " 获得嘲讽能力！")
		"draw_card":
			# 战吼：抽牌
			print("GameManager execute_unit_effects: 战吼抽牌 ", card.effect_value)
			for i in card.effect_value:
				if player_type == PlayerType.PLAYER:
					draw_card_for_player()
				else:
					draw_card_for_ai()
		"deathrattle_aoe":
			# 亡语：对所有敌方单位造成伤害（在死亡时触发）
			card.set_meta("deathrattle_aoe_damage", card.effect_value)
			log_message(card.card_name + " 获得亡语能力！")

func execute_buff_health_shield(player_type: PlayerType, buff_value: int):
	"""执行魔法护盾效果：给友方单位+生命值和护盾"""
	var board = player_board if player_type == PlayerType.PLAYER else ai_board
	
	if board.is_empty():
		log_message("战场上没有友方单位可以施加护盾！")
		return
	
	# 找到第一个有效的单位
	var target_unit = null
	for unit in board:
		if is_instance_valid(unit) and unit.health > 0:
			target_unit = unit
			break
	
	if target_unit == null:
		log_message("战场上没有有效的友方单位可以施加护盾！")
		return
	
	# 给目标单位加护盾
	target_unit.health += buff_value
	target_unit.max_health += buff_value
	target_unit.set_meta("has_shield", true)
	target_unit.update_card_display()
	log_message(target_unit.card_name + " 获得了魔法护盾！")

func execute_deathrattle_aoe(card: Control, player_type: PlayerType):
	"""执行亡语AOE效果"""
	if not card.has_meta("deathrattle_aoe_damage"):
		return
	
	var damage = card.get_meta("deathrattle_aoe_damage")
	var enemy_board = ai_board if player_type == PlayerType.PLAYER else player_board
	var enemy_player_type = PlayerType.AI if player_type == PlayerType.PLAYER else PlayerType.PLAYER
	
	print("GameManager execute_deathrattle_aoe: ", card.card_name, " 的亡语效果触发，对所有敌方单位造成 ", damage, " 点伤害")
	
	# 创建一个副本来避免在遍历时修改原数组
	var units_to_damage = enemy_board.duplicate()
	var units_to_remove = []
	
	# 对所有敌方单位造成伤害
	for unit in units_to_damage:
		# 检查单位是否仍然有效（未被释放）
		if is_instance_valid(unit) and unit.health > 0:
			unit.take_damage(damage)
			if unit.health <= 0:
				units_to_remove.append(unit)
	
	# 批量移除死亡单位
	for unit in units_to_remove:
		if is_instance_valid(unit):
			remove_unit_from_board(unit, enemy_player_type)
	
	log_message(card.card_name + " 的亡语效果触发！")

func show_spell_effect(card: Control, player_type: PlayerType):
	"""显示法术效果的视觉反馈"""
	print("GameManager show_spell_effect: 显示法术效果 ", card.card_name)
	
	# 获取主场景
	var main_scene = get_tree().current_scene
	if not main_scene:
		return
	
	# 尝试找到战场区域来显示法术效果
	var board_area = null
	if main_scene.has_node("GameUI/PlayerBoard/PlayerBoardContainer"):
		board_area = main_scene.get_node("GameUI/PlayerBoard/PlayerBoardContainer")
	elif main_scene.has_node("GameUI/PlayerBoard"):
		board_area = main_scene.get_node("GameUI/PlayerBoard")
	
	if board_area:
		# 创建法术效果的视觉表示
		var spell_effect = card.duplicate()
		spell_effect.modulate = Color.YELLOW  # 高亮显示
		spell_effect.scale = Vector2(1.2, 1.2)  # 稍微放大
		
		# 添加到战场区域
		board_area.add_child(spell_effect)
		
		# 创建动画效果
		var tween = create_tween()
		tween.set_parallel(true)
		tween.tween_property(spell_effect, "modulate", Color.WHITE, 0.5)
		tween.tween_property(spell_effect, "scale", Vector2(1.0, 1.0), 0.5)
		
		# 1秒后移除视觉效果
		await get_tree().create_timer(1.0).timeout
		if is_instance_valid(spell_effect):
			spell_effect.queue_free()

# 检查是否应该自动结束回合
func check_auto_end_turn():
	"""检查是否应该自动结束回合"""
	if current_turn != PlayerType.PLAYER or current_state != GameState.PLAYER_TURN:
		return
	
	# 获取Main节点的设置
	var main_node = get_tree().get_first_node_in_group("main")
	if main_node == null or not main_node.has_method("get_game_settings"):
		return
	
	var settings = main_node.get_game_settings()
	if not settings.auto_end_turn:
		return
	
	# 检查是否有可打出的卡牌
	var has_playable_cards = false
	for card in player_hand:
		if card and can_play_card(card, PlayerType.PLAYER):
			has_playable_cards = true
			break
	
	# 检查是否有可攻击的单位
	var has_attackable_units = false
	for card in player_board:
		if card and card.can_attack:
			has_attackable_units = true
			break
	
	# 如果没有可执行的操作，自动结束回合
	if not has_playable_cards and not has_attackable_units:
		log_message("[color=cyan]自动结束回合 - 无可执行操作[/color]")
		# 延迟1秒后自动结束回合，给玩家时间看到状态
		await get_tree().create_timer(1.0).timeout
		if current_turn == PlayerType.PLAYER and current_state == GameState.PLAYER_TURN:
			end_turn()

# 从GameManager测试提示框功能
func test_tooltip_from_gamemanager():
	print("=== GameManager: 开始测试提示框功能 ===")
	
	# 等待2秒确保所有节点都已初始化
	await get_tree().create_timer(2.0).timeout
	print("GameManager: 延迟2秒后开始执行提示框测试")
	
	# 获取Main节点
	var main_node = get_tree().get_first_node_in_group("main")
	if main_node == null:
		print("GameManager: 错误 - 无法找到Main节点")
		return
	
	print("GameManager: 找到Main节点，准备调用提示框测试")
	
	# 调用Main节点的提示框测试函数
	if main_node.has_method("test_tooltip_display"):
		main_node.test_tooltip_display()
		print("GameManager: 成功调用Main节点的test_tooltip_display函数")
	else:
		print("GameManager: 错误 - Main节点没有test_tooltip_display方法")

# 重新洗牌函数
func reshuffle_deck_for_player():
	"""为玩家重新洗牌"""
	if player_graveyard.is_empty():
		return
	
	# 将墓地卡牌重新加入牌库
	for card in player_graveyard:
		if card and is_instance_valid(card):
			# 重置卡牌状态
			if card.has_method("reset_card_state"):
				card.reset_card_state()
			player_deck.append(card)
	
	# 清空墓地
	player_graveyard.clear()
	
	# 洗牌
	player_deck.shuffle()
	
	log_message("玩家重新洗牌完成，牌库现有 " + str(player_deck.size()) + " 张卡牌")

func reshuffle_deck_for_ai():
	"""为AI重新洗牌"""
	if ai_graveyard.is_empty():
		return
	
	# 将墓地卡牌重新加入牌库
	for card in ai_graveyard:
		if card and is_instance_valid(card):
			# 重置卡牌状态
			if card.has_method("reset_card_state"):
				card.reset_card_state()
			ai_deck.append(card)
	
	# 清空墓地
	ai_graveyard.clear()
	
	# 洗牌
	ai_deck.shuffle()
	
	log_message("AI重新洗牌完成，牌库现有 " + str(ai_deck.size()) + " 张卡牌")

# 将卡牌送入墓地
func send_card_to_graveyard(card: Control, player_type: PlayerType):
	"""将卡牌送入墓地"""
	if not card or not is_instance_valid(card):
		return
	
	# 从战场移除
	if player_type == PlayerType.PLAYER:
		if card in player_board:
			player_board.erase(card)
		player_graveyard.append(card)
		log_message("玩家单位 " + card.card_name + " 进入墓地")
	else:
		if card in ai_board:
			ai_board.erase(card)
		ai_graveyard.append(card)
		log_message("AI单位 " + card.card_name + " 进入墓地")
	
	# 隐藏卡牌但不销毁，以便重新洗牌时使用
	card.visible = false

# 战场伤害结算系统
func resolve_battlefield_combat():
	"""回合结束时的战场伤害结算 - 包含英雄伤害溢出机制"""
	if player_board.is_empty() and ai_board.is_empty():
		return  # 双方都没有单位，无需结算
	
	log_message("[color=orange]⚔️ ===== 战场伤害结算开始 ===== ⚔️[/color]")
	
	# 记录需要销毁的单位
	var units_to_destroy: Array[Dictionary] = []
	
	# 计算双方单位的总伤害
	var player_total_damage = 0
	var ai_total_damage = 0
	
	# 计算玩家单位总攻击力
	for unit in player_board:
		if unit and is_instance_valid(unit):
			player_total_damage += unit.attack
	
	# 计算AI单位总攻击力
	for unit in ai_board:
		if unit and is_instance_valid(unit):
			ai_total_damage += unit.attack
	
	log_message("[color=cyan]🛡️ 玩家单位总攻击力: " + str(player_total_damage) + "[/color]")
	log_message("[color=red]⚔️ AI单位总攻击力: " + str(ai_total_damage) + "[/color]")
	
	# 如果没有战斗单位，跳过结算
	if player_total_damage == 0 and ai_total_damage == 0:
		log_message("[color=gray]💤 战场上没有单位，跳过伤害结算[/color]")
		return
	
	# 对玩家单位造成伤害，并计算溢出伤害
	var overflow_damage_to_player = 0
	if ai_total_damage > 0:
		log_message("[color=yellow]💥 AI单位对玩家单位发起攻击！[/color]")
		overflow_damage_to_player = await apply_battlefield_damage_with_overflow(player_board, ai_total_damage, PlayerType.PLAYER, units_to_destroy)
	
	# 对AI单位造成伤害，并计算溢出伤害
	var overflow_damage_to_ai = 0
	if player_total_damage > 0:
		log_message("[color=yellow]💥 玩家单位对AI单位发起攻击！[/color]")
		overflow_damage_to_ai = await apply_battlefield_damage_with_overflow(ai_board, player_total_damage, PlayerType.AI, units_to_destroy)
	
	# 销毁所有死亡的单位
	await destroy_units_after_combat(units_to_destroy)
	
	# 处理溢出伤害到英雄
	if overflow_damage_to_player > 0:
		log_message("[color=red]💀 剩余伤害溢出到玩家英雄: " + str(overflow_damage_to_player) + " 点！[/color]")
		await apply_hero_damage(PlayerType.PLAYER, overflow_damage_to_player)
	
	if overflow_damage_to_ai > 0:
		log_message("[color=red]💀 剩余伤害溢出到AI英雄: " + str(overflow_damage_to_ai) + " 点！[/color]")
		await apply_hero_damage(PlayerType.AI, overflow_damage_to_ai)
	
	log_message("[color=orange]✅ ===== 战场伤害结算结束 ===== ✅[/color]")

func apply_battlefield_damage_with_overflow(units: Array[Control], total_damage: int, player_type: PlayerType, units_to_destroy: Array[Dictionary]) -> int:
	"""对指定单位列表造成伤害，返回溢出伤害"""
	if units.is_empty() or total_damage <= 0:
		return total_damage  # 如果没有单位，所有伤害都溢出
	
	var player_name = "玩家" if player_type == PlayerType.PLAYER else "AI"
	log_message("[color=yellow]对" + player_name + "单位造成 " + str(total_damage) + " 点伤害[/color]")
	
	var remaining_damage = total_damage
	var units_total_health = 0
	
	# 计算所有单位的总生命值
	for unit in units:
		if unit and is_instance_valid(unit):
			units_total_health += unit.health
	
	log_message("[color=cyan]目标单位总生命值: " + str(units_total_health) + "[/color]")
	
	# 如果伤害超过单位总生命值，计算溢出
	var overflow_damage = 0
	if remaining_damage > units_total_health:
		overflow_damage = remaining_damage - units_total_health
		remaining_damage = units_total_health
		log_message("[color=orange]伤害超出单位承受能力，溢出伤害: " + str(overflow_damage) + "[/color]")
	
	# 按比例分配伤害给所有单位
	for unit in units:
		if not unit or not is_instance_valid(unit):
			continue
		
		# 按生命值比例分配伤害
		var damage_ratio = float(unit.health) / float(units_total_health)
		var damage_to_unit = int(remaining_damage * damage_ratio)
		
		# 确保不会造成负数伤害
		damage_to_unit = min(damage_to_unit, unit.health)
		
		if damage_to_unit > 0:
			# 应用伤害
			var old_health = unit.health
			unit.health -= damage_to_unit
			
			log_message("[color=white]" + unit.card_name + " 受到 " + str(damage_to_unit) + " 点伤害 (" + str(old_health) + " -> " + str(unit.health) + ")[/color]")
			
			# 更新卡牌显示
			unit.update_card_display()
			
			# 检查是否死亡
			if unit.health <= 0:
				units_to_destroy.append({
					"unit": unit,
					"player_type": player_type
				})
				log_message("[color=red]" + unit.card_name + " 被摧毁！[/color]")
			
			# 添加视觉反馈
			add_damage_visual_effect(unit, damage_to_unit)
	
	# 等待一下让玩家看到伤害效果
	await get_tree().create_timer(1.0).timeout
	
	return overflow_damage

func apply_battlefield_damage_to_units(units: Array[Control], total_damage: int, player_type: PlayerType, units_to_destroy: Array[Dictionary]):
	"""对指定单位列表造成伤害（保留原函数以兼容其他调用）"""
	await apply_battlefield_damage_with_overflow(units, total_damage, player_type, units_to_destroy)

func destroy_units_after_combat(units_to_destroy: Array[Dictionary]):
	"""战斗结算后销毁死亡的单位"""
	if units_to_destroy.is_empty():
		return
	
	log_message("[color=red]销毁 " + str(units_to_destroy.size()) + " 个死亡单位[/color]")
	
	for unit_data in units_to_destroy:
		var unit = unit_data.unit
		var player_type = unit_data.player_type
		
		if unit and is_instance_valid(unit):
			# 播放死亡动画
			await play_unit_death_animation(unit)
			
			# 将单位送入墓地
			send_card_to_graveyard(unit, player_type)
			
			# 从UI中移除
			if unit.get_parent():
				unit.get_parent().remove_child(unit)
	
	# 更新战场显示
	board_updated.emit()
	
	# 等待一下让玩家看到结果
	await get_tree().create_timer(0.5).timeout

func apply_hero_damage(target_player: PlayerType, damage: int):
	"""对英雄造成伤害，包含视觉效果和胜负判定"""
	if damage <= 0:
		return
	
	var player_name = "玩家" if target_player == PlayerType.PLAYER else "AI"
	log_message("[color=red]💀 " + player_name + "英雄受到 " + str(damage) + " 点伤害！[/color]")
	
	# 应用伤害
	if target_player == PlayerType.PLAYER:
		var old_health = player_health
		player_health -= damage
		log_message("[color=red]玩家生命值: " + str(old_health) + " -> " + str(player_health) + "[/color]")
		health_changed.emit(PlayerType.PLAYER, player_health)
		
		# 添加英雄受伤视觉效果
		await add_hero_damage_visual_effect(PlayerType.PLAYER, damage)
		
		# 检查是否死亡
		if player_health <= 0:
			log_message("[color=red]💀 玩家英雄被击败！[/color]")
			end_game(PlayerType.AI)
	else:
		var old_health = ai_health
		ai_health -= damage
		log_message("[color=red]AI生命值: " + str(old_health) + " -> " + str(ai_health) + "[/color]")
		health_changed.emit(PlayerType.AI, ai_health)
		
		# 添加英雄受伤视觉效果
		await add_hero_damage_visual_effect(PlayerType.AI, damage)
		
		# 检查是否死亡
		if ai_health <= 0:
			log_message("[color=red]💀 AI英雄被击败！[/color]")
			end_game(PlayerType.PLAYER)

func add_hero_damage_visual_effect(target_player: PlayerType, damage: int):
	"""为英雄添加受伤视觉效果"""
	# 获取对应的生命值标签
	var health_label: Label
	if target_player == PlayerType.PLAYER:
		health_label = get_node("/root/Main/GameUI/BottomPanel/PlayerInfo/PlayerHealthLabel")
	else:
		health_label = get_node("/root/Main/GameUI/TopPanel/AIInfo/AIHealthLabel")
	
	if not health_label:
		return
	
	# 创建伤害数字显示
	var damage_label = Label.new()
	damage_label.text = "-" + str(damage)
	damage_label.add_theme_color_override("font_color", Color.RED)
	damage_label.add_theme_font_size_override("font_size", 24)
	damage_label.z_index = 1000
	
	# 添加到场景中
	get_tree().current_scene.add_child(damage_label)
	
	# 设置位置（在生命值标签旁边）
	damage_label.global_position = health_label.global_position + Vector2(100, -20)
	
	# 创建动画效果
	var tween = create_tween()
	tween.set_parallel(true)
	
	# 向上飘动并淡出
	tween.tween_property(damage_label, "global_position", damage_label.global_position + Vector2(0, -50), 1.5)
	tween.tween_property(damage_label, "modulate:a", 0.0, 1.5)
	
	# 生命值标签闪烁效果
	var health_tween = create_tween()
	health_tween.set_loops(3)
	health_tween.tween_property(health_label, "modulate", Color.RED, 0.1)
	health_tween.tween_property(health_label, "modulate", Color.WHITE, 0.1)
	
	# 等待动画完成
	await tween.finished
	
	# 清理伤害标签
	if damage_label and is_instance_valid(damage_label):
		damage_label.queue_free()

func add_damage_visual_effect(unit: Control, damage: int):
	"""为单位添加受伤视觉效果"""
	if not unit or not is_instance_valid(unit):
		return
	
	# 创建伤害数字显示
	var damage_label = Label.new()
	damage_label.text = "-" + str(damage)
	damage_label.add_theme_color_override("font_color", Color.RED)
	damage_label.add_theme_font_size_override("font_size", 20)
	damage_label.position = unit.position + Vector2(0, -30)
	damage_label.z_index = 100
	
	# 添加到场景
	if unit.get_parent():
		unit.get_parent().add_child(damage_label)
		
		# 创建动画
		var tween = create_tween()
		tween.parallel().tween_property(damage_label, "position", damage_label.position + Vector2(0, -50), 1.0)
		tween.parallel().tween_property(damage_label, "modulate:a", 0.0, 1.0)
		
		# 动画结束后删除标签
		tween.tween_callback(damage_label.queue_free)
	
	# 让单位闪红表示受伤
	var original_modulate = unit.modulate
	unit.modulate = Color.RED
	
	var flash_tween = create_tween()
	flash_tween.tween_property(unit, "modulate", original_modulate, 0.3)

func play_unit_death_animation(unit: Control):
	"""播放单位死亡动画"""
	if not unit or not is_instance_valid(unit):
		return
	
	# 创建死亡动画
	var death_tween = create_tween()
	death_tween.parallel().tween_property(unit, "scale", Vector2.ZERO, 0.5)
	death_tween.parallel().tween_property(unit, "modulate:a", 0.0, 0.5)
	
	# 等待动画完成
	await death_tween.finished
	if unit.get_parent():
		unit.get_parent().remove_child(unit)
